package com.ds.infra.rpc.core.loadbalance;

import com.ds.infra.rpc.registry.model.ServiceInstance;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 作用：轮询-负载均衡（线程安全）
 *
 * @author WeiShaoying
 */
@Slf4j
public class RoundRobinLoadBalance implements LoadBalance {

    private final AtomicInteger counter = new AtomicInteger(0);

    @Override
    public Map<String, Object> select(List<Map<String, Object>> instances) {
        if (instances.isEmpty()) {
            log.error("No available instances");
            throw new RuntimeException("No service instance available");
        }

        int index = Math.abs(counter.getAndIncrement() % instances.size());
        Map<String, Object> selected = instances.get(index);
        log.debug("Selected instance: {}", selected.get("serviceAddress"));
        return selected;
    }

    @Override
    public ServiceInstance selectInstance(List<ServiceInstance> instances) {
        return null;
    }
}
